<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card v-if="parentQuestion.id" class="box-card">
          <div slot="header" class="clearfix">
            <span>
              主题目
              <el-tag effect="dark" size="mini">{{
                parentQuestion.name
                  ? parentQuestion.name
                  : questionType[parentQuestion.type]
              }}</el-tag>
            </span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="goBack()"
              >返回主题目</el-button
            >
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex
              :katex-content="parentQuestion.title"
              index="parentQuestionTitle"
            />
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex
              :katex-content="parentQuestion.materials"
              index="parentQuestionMaterials"
            />
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row
              v-if="question.id"
              :gutter="20"
              class="cardHeader"
              style="display: flex"
            >
              <el-col style="flex: 1" />
            </el-row>
            <el-row
              v-if="!question.readonly && !isEdit"
              :gutter="20"
              class="cardHeader"
              style="display: flex"
            >
              <el-col style="flex: 1" />
              <el-col
                v-if="question.id"
                class="cardHeader"
                style="width: 250px; margin-top: 4px"
              >
                <el-button
                  v-if="!question.readonly && !isEdit"
                  class="flbtn"
                  size="small"
                >
                  <router-link
                    :to="'/work/questionList?workTemplateId=' + workTemplateId"
                  >
                    返回列表</router-link
                  >
                </el-button>
                <el-button
                  v-if="!question.readonly && !isEdit"
                  class="flbtn"
                  size="small"
                  type="primary"
                  @click="isEdit = true"
                  >编辑</el-button
                >
              </el-col>
            </el-row>
          </div>
          <div class="content">
            <el-form
              ref="question"
              :rules="rules"
              :model="question"
              label-width="100px"
            >
              <el-form-item label="题目" prop="title">
                <myEdit :disabled="readonly" v-model="question.title" />
              </el-form-item>
              <el-form-item label="分值" prop="title">
                <el-input-number
                  :disabled="readonly"
                  v-model="question.score"
                  :min="0"
                  :max="100"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="题目类型">
                <el-select
                  :disabled="readonly"
                  v-model="question.type"
                  size="mini"
                  placeholder="请选择题目类型"
                >
                  <el-option
                    v-for="(key, value) in questionType"
                    :key="key"
                    :label="key"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="题目类型别名">
                <el-input
                  :disabled="readonly"
                  v-model="question.name"
                  :placeholder="typeName"
                  size="mini"
                />
              </el-form-item>
              <el-form-item
                v-if="
                  question.type === '1' ||
                  question.type === '2' ||
                  question.type === '3'
                "
                label="答案"
              >
                <el-checkbox-group
                  :disabled="readonly"
                  v-model="question.answer"
                  @change="handleAnswer"
                >
                  <div v-for="item in question.select" :key="item.select">
                    <el-checkbox :label="item.select">
                      <el-select
                        :disabled="readonly"
                        v-model="item.select"
                        style="width: 65px"
                        size="small"
                        placeholder
                      >
                        <el-option
                          v-for="item in selectNotUse"
                          :key="item"
                          :label="item"
                          :value="item"
                        />
                      </el-select>
                      <myEdit
                        :disabled="readonly"
                        v-model="item.content"
                        :inline="true"
                        :use-dialog="true"
                        size="small"
                      />
                      <el-link
                        :disabled="readonly"
                        :underline="false"
                        icon="el-icon-error"
                        type="danger"
                        @click="removeItem(item)"
                      />
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
                <el-checkbox v-if="!readonly" disabled>
                  <el-select
                    v-model="newSelect.select"
                    style="width: 65px"
                    size="small"
                    placeholder
                  >
                    <el-option
                      v-for="item in selectNotUse"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                  <myEdit
                    :disabled="readonly"
                    v-model="newSelect.content"
                    :inline="true"
                    :use-dialog="true"
                    size="small"
                  />
                  <el-link
                    :underline="false"
                    icon="el-icon-circle-plus"
                    type="primary"
                    @click="addItem"
                  />
                </el-checkbox>
              </el-form-item>
              <el-form-item
                v-else-if="
                  question.type === '5' ||
                  question.type === '6' ||
                  question.type === '7'
                "
                label="答案"
              >
                <myEdit :disabled="readonly" v-model="question.answer[0]" />
              </el-form-item>
              <div
                v-if="
                  question.type === '1' ||
                  question.type === '2' ||
                  question.type === '3' ||
                  question.type === '5' ||
                  question.type === '6' ||
                  question.type === '7'
                "
              >
                <el-form-item label="解析">
                  <myEdit :disabled="readonly" v-model="question.analyze" />
                </el-form-item>
              </div>
              <el-form-item>
                <el-button
                  v-if="!readonly"
                  type="info"
                  @click="saveQuestion(false)"
                  >保存</el-button
                >
                <el-button v-if="!readonly" type @click="saveQuestion(true)"
                  >保存并继续添加</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card
          v-if="
            question.type === '4' ||
            question.type === '8' ||
            question.type === '9' ||
            question.type === '10'
          "
          class="box-card"
        >
          <div slot="header" class="clearfix">
            <el-row :gutter="20">
              <el-col :span="20" class="cardHeader">
                <span>
                  子题目
                  <span>(注*支持拖拽排序)</span>
                </span>
              </el-col>
              <el-col :span="4" class="cardHeader">
                <el-button
                  v-if="!readonly && question.id"
                  type="primary"
                  size="mini"
                  @click="saveSonQuestion()"
                  >添加子题目</el-button
                >
              </el-col>
            </el-row>
          </div>
          <draggable
            :disabled="readonly"
            v-model="sonQuestions"
            @update="updateSortQuestion"
          >
            <el-card
              v-for="(sonQuestion, index) in sonQuestions"
              :key="sonQuestion.id"
              class="questionItem"
            >
              <el-row>
                <el-col :span="1">题目:</el-col>
                <el-col :span="1">{{ index + 1 }}</el-col>
                <el-col :span="1" class="fg">|</el-col>
                <el-col :span="10">
                  <span class="questionTitle" v-html="sonQuestion.title" />
                </el-col>
                <el-col :span="2">
                  <el-tag effect="dark" size="mini">{{
                    questionType[sonQuestion.type]
                  }}</el-tag>
                </el-col>
                <el-col :span="1" class="fg">|</el-col>

                <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                <el-col v-if="!readonly" :span="2">
                  <el-link
                    icon="el-icon-edit"
                    @click="sonQuestionInfo(sonQuestion.id)"
                    >编辑</el-link
                  >
                </el-col>
                <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                <el-col v-if="!readonly" :span="2">
                  <el-link
                    icon="el-icon-delete"
                    type="danger"
                    @click="deleteQuestion(sonQuestion.id)"
                    >删除</el-link
                  >
                </el-col>
              </el-row>
            </el-card>
          </draggable>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="phoneShow">
          <div class="phoneContent">
            <phone
              :question="questionShow"
              :parent-question="parentQuestionShow"
              :knowledgePoints="[]"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Sticky from "@/components/Sticky";
import { uploadAli } from "@/api/upload.js";
import myVideo from "@/components/video/myVideo";
import draggable from "vuedraggable";
import phone from "@/components/phone";
import myEdit from "@/components/myEdit";
import { addQuestionToWork, getQuestionToWork } from "@/api/work.js";
import {
  questionList,
  saveQuestion,
  questionInfo,
  commitCheck,
  rejectCheck,
  commitReview,
  rejectReview,
  deleteQuestion,
  review,
  questionSort,
  questionUpAndDown,
} from "@/api/question.js";
import katex from "@/components/phone/katex";
import { getAreaList } from "@/api/area.js";
import { getSubjectTypeList } from "@/api/subjectType.js";
import { getTestTypeList } from "@/api/testType.js";
import { getQueryObject } from "@/utils/index";
export default {
  name: "QuestionInfo",
  components: {
    Sticky,
    myVideo,
    draggable,
    phone,
    myEdit,
    katex,
  },
  filters: {},
  data() {
    return {
      rules: {
        title: [{ required: true, message: "题目名称必填", trigger: "blur" }],
      },
      workTemplateId: -1,
      loading: false,
      questionShow: {},
      parentQuestionShow: {},
      editContent: "",
      loading: false,
      point: "",
      radio: "1",
      sonQuestions: [],
      qPoint: "",
      dialogFormVisible: false,
      video: {
        sources: [],
        options: {
          autoplay: false,
          poster: "",
        },
      },
      selectAnswer: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      questionType: {
        1: "单选题",
        2: "多选题",
        3: "判断题",
        4: "情景题",
        5: "简答题",
        6: "辨析题",
        7: "填空",
        8: "完形填空",
        9: "阅读理解",
        10: "背景题",
      },
      newSelect: {
        select: "",
        content: "",
      },
      isEdit: false,
      parentQuestion: {
        id: null,
        title: "",
      },
      beSimilarQuestion: [],
      question: {
        id: null,
        score: 0,
        testStructure: "",
        select: [
          {
            select: "A",
            content: "",
          },
          {
            select: "B",
            content: "",
          },
          {
            select: "C",
            content: "",
          },
          {
            select: "D",
            content: "",
          },
        ],
        answer: [],
        score: 1,
        type: "1",
        title: "",
        videoAnalyze: "",
        analyze: "",
        difficultyLevel: 1,
        questionType: 1,
        isOfficialQuestion: 0,
        officialQuestionSource: "",
        year: "",
      },
      search: true,
      questionUpAndDown: {
        up: undefined,
        down: undefined,
      },
      questionUpDisabled: true,
      questionDownDisabled: true,
    };
  },
  computed: {
    typeName() {
      return this.questionType[this.question.type];
    },
    selectNotUse() {
      const arr = this.selectAnswer.filter((item) => {
        const x = this.question.select.find((s) => s.select === item);
        return !x;
      });
      return arr;
    },
    readonly: function () {
      return (
        (!this.isEdit || this.question.readonly) && this.question.id != null
      );
    },
  },
  watch: {
    question: {
      handler(newValue, old) {
        if (newValue.title && newValue.title.length > 4) {
          if (this.search) {
            let title = newValue.title;
            if (title.length > 800) {
              title = title.substring(0, 800);
            }
          }
        } else {
          this.beSimilarQuestion = [];
          this.search = true;
        }
        this.questionShow = this.question;
        this.parentQuestionShow = this.parentQuestion;
      },
      deep: true,
    },
    parentQuestion: {
      handler(newValue, old) {
        this.parentQuestionShow = this.parentQuestion;
      },
      deep: true,
    },
  },
  created() {
    this.workTemplateId = getQueryObject()["workTemplateId"];
    if (this.$router.currentRoute.params.question) {
      this.question.id = this.$router.currentRoute.params.question.id;
      this.workTemplateId = this.$router.currentRoute.params.question.workTemplateId;
    }
    this.questionInfo();
    if (this.workTemplateId) {
      this.getWork();
    }
  },
  methods: {
    getWork() {
      if (this.workTemplateId && this.question.id) {
        getQuestionToWork(this.workTemplateId, this.question.id).then((res) => {
          this.question.score = res.data;
        });
      }
    },
    query() {
      this.isknowledgePoint = false;
      this.initknowledgePoint = true;
      this.$nextTick(() => {
        this.isknowledgePoint = true;
      });
    },
    props() {
      const that = this;
      return {
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          let id;
          if (!that.initknowledgePoint) {
            id = node.value;
          }
          that.initknowledgePoint = false;
          that.queryPoint(id).then((res) => {
            const nodes = res.data.map((item) => ({
              value: item.id,
              label: item.name,
              leaf: item.haveNext === 0,
            }));
            resolve(nodes);
          });
        },
      };
    },
    deleteQuestion(id) {
      deleteQuestion(id).then((res) => {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        questionList({
          parentId: this.question.id,
          sort: "asc_q.sort",
          isNew: 2,
          pageNo: 1,
          pageSize: 40,
        }).then((res) => {
          this.sonQuestions = res.data;
        });
      });
    },
    querySearchAsync(str) {
      if (str) {
        this.loading = true;
        searchPoint({ name: str }).then((res) => {
          this.knowledgePointList = res.data;
          this.loading = false;
        });
      }
    },
    showQuestion(id) {
      this.question.id = id;
      this.parentQuestion = {
        id: null,
        title: "",
      };
      this.questionInfo();
    },
    show(id) {
      questionInfo(id).then((res) => {
        const data = res.data;
        if (data.answer) {
          data.answer = JSON.parse(data.answer);
        }
        this.questionShow = data;
        if (this.questionShow.parentId !== 0) {
          questionInfo(this.questionShow.parentId).then((item) => {
            this.parentQuestionShow = item.data;
          });
        }
      });
    },
    updateSortQuestion(evt) {
      const changeTags = this.sonQuestions[evt.newIndex];
      let sort;
      let beforeSort;
      let afterSort;
      if (evt.newIndex === 0) {
        beforeSort = this.sonQuestions[evt.newIndex + 1].sort - 50;
      } else {
        beforeSort = this.sonQuestions[evt.newIndex - 1].sort;
      }
      if (evt.newIndex === this.sonQuestions.length - 1) {
        afterSort = this.sonQuestions[evt.newIndex - 1].sort + 50;
      } else {
        afterSort = this.sonQuestions[evt.newIndex + 1].sort;
      }
      sort =
        Math.floor(Math.random() * (afterSort - beforeSort + 1)) + beforeSort;
      questionSort(changeTags.id, sort).then((res) => {
        questionList({
          parentId: this.question.id,
          sort: "asc_q.sort",
          isNew: 2,
          pageNo: 1,
          pageSize: 40,
        }).then((res) => {
          this.sonQuestions = res.data;
        });
      });
    },
    sonQuestionInfo(id) {
      this.question.id = id;
      this.questionInfo();
    },
    goBack() {
      this.question = {
        id: this.parentQuestion.id,
      };
      this.parentQuestion = {
        id: null,
        title: "",
      };
      this.questionInfo();
    },
    saveSonQuestion() {
      this.parentQuestion = this.question;
      this.question = {
        id: null,
        testStructure: "",
        questionType: 1,
        select: [
          {
            select: "A",
            content: "",
          },
          {
            select: "B",
            content: "",
          },
          {
            select: "C",
            content: "",
          },
          {
            select: "D",
            content: "",
          },
        ],
        answer: [],
        score: 1,
        type: "1",
        title: "",
        videoAnalyze: "",
        analyze: "",
        difficultyLevel: 1,
        questionType: 2,
        isOfficialQuestion: 0,
        officialQuestionSource: "",
        parentId: this.parentQuestion.id,
        year: "",
      };
    },
    questionInfo() {
      const id = this.question.id || this.$router.currentRoute.query.id;
      if (id) {
        this.question.id = id;
        questionList({
          parentId: id,
          isNew: 2,
          sort: "asc_q.sort",
          pageNo: 1,
          pageSize: 40,
        }).then((res) => {
          this.sonQuestions = res.data;
          this.sonQuestions.readonly = false;
        });
        questionInfo(id).then((res) => {
          const data = res.data;
          if (data.answer) {
            data.answer = JSON.parse(data.answer);
          }
          const score = this.question.score;
          this.question = res.data;
          this.question.readonly = false;
          if (!this.question.score) {
            this.question.score = score;
          }
          if (this.question.checkPeople === 0) {
            this.question.checkPeople = null;
          }
          if (this.question.reviewPeople === 0) {
            this.question.reviewPeople = null;
          }
          this.question.type = this.question.type + "";
          if (this.question.videoAnalyze) {
            this.videoUploadStatus = 2;
            this.video.sources.push({
              src: this.question.videoAnalyze,
              type: "video/mp4",
            });
          }
          if (this.question.year) {
            this.question.year = this.question.year + "";
          }
          if (this.question.questionType === 2) {
            questionInfo(this.question.parentId).then((res) => {
              this.parentQuestion = res.data;
            });
          }
        });
      }
    },
    saveQuestion(flag) {
      let vaildFlag;
      this.$refs["question"].validate((valid) => {
        vaildFlag = valid;
        if (!valid) {
          return false;
        }
      });
      if (!vaildFlag) {
        return;
      }
      const question = this.question;
      if (!question.name) {
        question.name = this.typeName;
      }
      question.isNew = 2;
      saveQuestion(question).then((res) => {
        this.question.id = res.data.id;
        addQuestionToWork(
          this.workTemplateId,
          this.question.id,
          this.question.score
        )
          .then((res) => {
            this.getWork();
          })
          .catch((err) => {
            this.$confirm("题目与作业关联失败,是否重新关联?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "danger",
            })
              .then(() => {
                addQuestionToWork(
                  this.workTemplateId,
                  this.question.id,
                  this.question.score
                )
                  .then((res) => {
                    this.getWork();
                  })
                  .catch((err) => console.log(err));
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消关联",
                });
              });
          });
        this.$message.success("更新成功!");
        if (!flag) {
          this.questionInfo();
          this.isEdit = false;
        } else {
          this.question = {
            id: null,
            testStructure: "",
            questionType: this.question.questionType,
            select: [
              {
                select: "A",
                content: "",
              },
              {
                select: "B",
                content: "",
              },
              {
                select: "C",
                content: "",
              },
              {
                select: "D",
                content: "",
              },
            ],
            answer: [],
            score: 1,
            type: "1",
            title: "",
            videoAnalyze: "",
            analyze: "",
            difficultyLevel: 1,
            parentId: this.parentQuestion.id,
            isOfficialQuestion: 0,
            officialQuestionSource: "",
            year: "",
          };
        }
      });
    },
    handleAnswer() {
      this.question.answer = this.question.answer.filter((item) =>
        this.question.select.find((s) => s.select === item)
      );
    },
    removeItem(item) {
      this.question.select = this.question.select.filter((i) => i !== item);
    },
    addItem() {
      if (this.newSelect.select) {
        this.question.select.push(this.newSelect);
        this.newSelect = {
          select: "",
          content: "",
        };
      }
    },
  },
};
</script>
<style>
.sticky {
  height: 40px;
  background-color: #f2f6fc;
}
.questionItem {
  margin-top: 5px;
}
.questionItem .el-card__body {
  padding: 12px;
}
.questionTitle p {
  margin: 0px;
}
.likeQuestion p {
  margin: 0px;
}
</style>
<style scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.videoAnalyze {
  width: 70%;
}
.phoneShow {
  width: 400px;
  margin-top: 25px;
  position: fixed;
}
.el-rate {
  height: 40px;
  line-height: 50px;
}
.knowledgePointForm {
  margin-top: 25px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.progress {
  margin-top: 10px;
}
.box-card {
  width: 90%;
  margin-left: 5%;
  margin-top: 25px;
  margin-bottom: 25px;
}

.testItem {
  font-size: 12px;
  margin-left: 2%;
  line-height: 40px;
}

.testItemContent {
  margin-left: 10px;
}

.testName {
  font-size: 18px;
  margin-left: 8%;
}
.content {
  margin-bottom: 60px;
}
.phoneContent {
  margin: 0px auto;
  width: 320px;
}
</style>
